package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.logger.LogMessageType;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.User;
import com.conversationboard.site.Site;
import com.conversationboard.validate.InputChecker;
import com.conversationboard.validate.bbcode.Validator;

@WebServlet(name = "AdminOpenCloseControllerServlet", urlPatterns = "/Admin/AdminOpenCloseControllerServlet")
public class AdminOpenCloseControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -4311539862413524895L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {

			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			User user = User.get(request.getUserPrincipal().getName());

			if (!SecurityChecks.passes(request, user, this)) {
				return;
			}

			if (!user.isSiteAdmin()) {
				return;
			}

			/* User is site admin and has passed checks - set toggle the site */

			Site.setShut(!Site.isShut());

			/* Set the domain name correctly when the site is opened */

				if (!Site.isShut()) {

				String domainName = request.getServerName();

				if (request.getServerPort() != 80) {
					domainName += ":" + request.getServerPort();
				}

				Logger.log(new Date(), "<b><span class='red'>Setting domain name to:</span></b> " + domainName, null, LogMessageType.SYSTEM);

				Configuration.getInstance().setDomainName(domainName);
			}

			InputChecker.refresh();
			Validator.refresh();

			response.sendRedirect(Configuration.getInstance().getRoot() + "/index.jsp");

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
